import React, { useCallback, useMemo, useEffect, useState, useRef } from "react";
import Taro from "@tarojs/taro";
import { View, Image, Text } from "@tarojs/components";
import { observer } from "mobx-react";
import i18n from "i18n-js";
import { GStyleSheet } from "@/utils/DarkMode";
import PageContainer from "@/components/PageContainer";
import deviceListModel from "@/models/deviceList";
import { getItemForPk } from "@/config/product";
import ListItem from "@/components/ListItem";
import Switch from "@/components/Switch";
import { fetchDeviceAlarmSetting, updateDeviceAlarmSetting } from "@/services/deviceAlarm";
import { filterDeviceCanShare } from "../share/shareList/models";

const dstyle = GStyleSheet.create({
  scroll: {

  },
  noneTips: {
    textAlign: 'center',
    padding: '50PX 20PX',
    width: '100%',
    display: 'block',
    boxSizing: 'border-box',
    color: '#999999',
    fontSize: 14,
  },
  bottomText: {
    color: '#007AFE',
    position: 'absolute',
    width: '100%',
    bottom: '30PX',
    left: 0,
    textAlign: 'center'
  },
  icon: {
    width: 24,
    height: 24,
  }
});

const DeviceNoti: React.FC = () => {
  const styles = dstyle.style
  const [alarmState, setAlarmState] = useState({})
  const cacheRef = useRef({})

  const devices = deviceListModel.data.filter(item => {
    const productConfig = getItemForPk(item.productKey)
    if (productConfig && productConfig.supportDeviceAlarm && filterDeviceCanShare(item)) {
      return true
    }
  })

  useEffect(() => {
    devices.map(async (item) => {
      const data = await fetchDeviceAlarmSetting(item.mac, item.productKey)
      if (data.success) {
        setAlarmState((oValue) => {
          oValue[item.deviceId] = data.data?.wechatNotice
          return {...oValue}
        })

        cacheRef.current[item.deviceId] = data.data;
      }
    })
  }, [])


  const switchChange = async (id, val) => {
    const currentData = cacheRef.current[id]
    currentData['wechatNotice'] = val
    const data = await updateDeviceAlarmSetting(currentData)
    if (!data.success) {
      // 异常处理
    }
    setAlarmState((oValue) => {
      oValue[id] = val
      return {...oValue}
    })
  }

  const switchAllChange = async (val) => {
    Taro.showLoading()
    for (let key in devices) {
      const id = devices[key].deviceId
      await switchChange(id, val)
    }
    Taro.hideLoading()

  }

  let isAllCheck = true
  Object.values(alarmState).map(item => {
    isAllCheck = isAllCheck && !!item
  })

  console.log('alarmState', alarmState)

  return (
    <PageContainer title={i18n.t('设备订阅管理')} >
      <ListItem extra={
        <Switch checked={isAllCheck} onChange={(e) => { switchAllChange(e) }} />
      }
      >
        {i18n.t('允许通知')}
      </ListItem>
      {
        devices.map((item, index) => {
          const productConfig = getItemForPk(item.productKey)
          return (
            <ListItem 
              extra={
                <Switch checked={alarmState[`${item.deviceId}`]} onChange={(e) => { switchChange(item.deviceId, e) }} />
              }
              key={item.deviceId} 
              icon={<Image src={productConfig.icon} style={styles.icon}></Image>}
            >
              {item.name}
            </ListItem>
          )
        })
      }

      {
        devices.length === 0 && (
          <Text style={styles.noneTips}>{i18n.t('暂无数据')}</Text>
        )
      }
      
      <Text onClick={() => {
        Taro.navigateTo({
          url: '/pages/alarmPush/alarmPushTips'
        })
      }} style={styles.bottomText}
      >
        如何开启微信订阅消息？
      </Text>
    </PageContainer >
  );
}

export default observer(DeviceNoti);
